<template>
  <div>
    <h2>会员管理</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/AdminMain/AdminHome">主页</el-breadcrumb-item>
      <el-breadcrumb-item>会员管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <i class="el-icon-s-order" style="margin-right: 5px;"></i>会员信息表
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%;">
        <el-table-column prop="memberAccount" label="会员账号/卡号" />
        <el-table-column prop="memberName" label="姓名" />
        <el-table-column prop="cardTime" label="办卡时间" :formatter="formatDate" />
        <el-table-column prop="memberGender" label="性别" />
        <el-table-column prop="memberAge" label="年龄" />
        <el-table-column prop="memberPhone" label="联系方式" />
        <el-table-column prop="memberHeight" label="身高" />
        <el-table-column prop="memberWeight" label="体重" />
        <el-table-column prop="cardClass" label="购买课时" />
        <el-table-column prop="cardNextClass" label="剩余课时" />
        <el-table-column label="操作">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="onEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="onDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 中文分页组件 -->
      <el-pagination
          style="margin-top: 20px; text-align: center"
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
      >
        <!-- 替换 total 显示为“总人数” -->
        <template #total>
          共 {{ total }} 人
        </template>

        <!-- 替换 jumper 显示为“跳转到 X 页” -->
        <template #jumper>
          跳转到
          <el-input
              class="el-pagination__editor is-in-pagination"
              v-model.number="jumperPage"
              type="number"
              size="small"
              @keyup.enter.native="jumpToPage"
              :min="1"
              :max="Math.ceil(total / pageSize)"
          />
          页
        </template>
      </el-pagination>

      <div style="text-align:center;margin-top:20px;">
        <el-button type="success" @click="onAdd">添加会员信息</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from "dayjs";

const router = useRouter()

const tableData = ref([])
const loading = ref(false)

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const jumperPage = ref(null)

// 拉取数据方法（分页）
const fetchData = () => {
  loading.value = true
  axios.get('/server/member/search', {
    params: {
      page: currentPage.value,
      size: pageSize.value
    }
  })
      .then(response => {
        if (response.data.code === 200) {
          tableData.value = response.data.data.records
          total.value = response.data.data.total
        } else {
          ElMessage.error('获取数据失败: ' + response.data.message)
        }
      })
      .catch(error => {
        console.error('获取会员数据失败:', error)
        ElMessage.error('加载会员数据失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 页码变化时刷新数据
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchData()
}

// 自定义跳页
const jumpToPage = () => {
  if (
      jumperPage.value >= 1 &&
      jumperPage.value <= Math.ceil(total.value / pageSize.value)
  ) {
    currentPage.value = jumperPage.value
    fetchData()
  } else {
    ElMessage.warning('请输入有效页码')
  }
}

// 首次加载数据
onMounted(() => {
  fetchData()
})

// 编辑会员
const onEdit = (row) => {
  router.push({
    path: '/AdminMain/EditMember',
    query: { memberAccount: row.memberAccount }
  })
}

// 删除会员（前端模拟）
const onDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除会员账号为 ' + row.memberAccount + ' 的会员吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    tableData.value = tableData.value.filter(item => item.memberAccount !== row.memberAccount)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 添加会员
const onAdd = () => {
  router.push({
    path: '/AdminMain/AddMember'
  })
}

//时间格式
const formatDate = (row, column, cellValue) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : ''
}
</script>

<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}
</style>
